Lua中math常用的api整理 | 您所在的位置:网站首页 › lua mathrandom › Lua中math常用的api整理 |
在使用 Lua 进行开发的过程中,经常涉及到一些 math 数学库,这里对一些使用频率比较高的 api 进行整理: 1、math.min(x, ...) 和 math.max(x, ...) :返回参数中的较小值、较大值。 local x, y = 10, 100 local min = math.min(x, y) local max = math.max(x, y) print(min, max) -- 10 1002、math.ceil(x) 和 math.floor(x) :向上取整、向下取整。 local x = 10.5 local ceil = math.ceil(x) local floor = math.floor(x) print(ceil, floor) -- 11 103、math.sqrt(x) :返回 x 的平方根。 local x = 16 local sqrt = math.sqrt(x) print(sqrt) -- 44、math.abs(x) :返回 x 的绝对值。 local x = -16 local abs = math.abs(x) print(abs) -- 165、math.fmod(x, y) :取模运算,返回 x 除以 y 的余数。 local x, y = 16, 3 local fmod = math.fmod(x, y) print(fmod) -- 1ps 还有一个和 math.fmod 比较类似的 math.modf(x),math.modf(x) 是返回 x 的整数部分和小数部分,返回的第二个结果一定是浮点数。 local x = 10.56 local modf1, modf2 = math.modf(x) print(modf1, modf2) -- 10 0.566、math.pi :返回 π 的值。 local pi = math.pi print(pi) -- 3.14159265358987、math.pow(x, y) :返回 x 的 y 次方。 local x, y = 2, 4 local pow = math.pow(x, y) print(pow) -- 168、math.random([m, [ ,n]]) :返回一个随机数,当不带参数调用时, 返回一个【0, 1】区间内一致分布的浮点伪随机数,当以两个整数 m 与 n 调用时,返回一个【m, n】区间 内一致分布的整数伪随机数(值 m-n 不能是负数,且必须在 Lua 整数的表示范围内), 调用 math.random(n) 等价于 math.random(1, n) 。 math.randomseed(os.time()) print(math.random()) -- 返回一个0-1之间的随机数 print(math.random(6)) -- 返回一个1-6之间的随机数 print(math.random(10, 20)) -- 返回一个10-20之间的随机数注:math.random 应该和获取随机数种子的函数 math.randomseed(x) 配合使用,在使用 math.random 之前调用一下 math.randomseed(os.time()) 即可,一般使用系统时间来作为随机数种子! --------------------add on Oct. 14, 2019-------------------- 生成随机数: math.randomseed(tonumber(tostring(os.time()):reverse():sub(1,6))) for i = 1, 5 do print(math.random(5)) end
参考:云风大大的 Lua5.3 参考手册! |
CopyRight 2018-2019 实验室设备网 版权所有 |